package jmu.cze.controller;

import jmu.cze.service.NoteService;
import jmu.cze.service.PersonService;
import jmu.cze.service.ProductSerivce;
import jmu.cze.until.JsonUtil;
import jmu.cze.until.UUIDUtil;
import jmu.cze.vo.Message;
import jmu.cze.vo.Person;
import jmu.cze.vo.Product;
import jmu.cze.vo.Revert;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

@Controller
@RequestMapping("/admin")
public class AdminController {

    private ProductSerivce productSerivce;
    private NoteService noteService;
    private PersonService personService;

    @Resource(name = "productSerivceImpl")
    public void setProductSerivce(ProductSerivce productSerivce) {
        this.productSerivce = productSerivce;
    }

    @Resource(name = "noteServiceImpl")
    public void setNoteService(NoteService noteService) {
        this.noteService = noteService;
    }

    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    @GetMapping("/manageProduct/{page}")
    public String manageProduct(@PathVariable int page, Model model) {
        if(page<1) page=1;
        model.addAttribute("list", productSerivce.getProducts(page, 10));
        model.addAttribute("count",productSerivce.countAll());
        return "admin/product";
    }

    @GetMapping("/searchProduct/{kw}")
    public String searchProduct(@PathVariable("kw") String kw, Model model){
        model.addAttribute("list", productSerivce.search(kw));
        return "admin/product";
    }

    @GetMapping("modifyProduct/{id}")
    public String getProduct(@PathVariable int id, Model model){
        model.addAttribute("product",productSerivce.findByID(id));
        return "admin/modifyProduct";
    }

    @PostMapping("/addProduct")
    public String addProduct(@RequestParam("file") MultipartFile img, Product product, HttpSession session, Model model) throws IOException {
        if (img.getSize() > 0) {//判断是否有上传文件
            String path = session.getServletContext().getRealPath("static/images");// 得到项目在服务器的真实根路径
            String fileName = img.getOriginalFilename();// 得到文件的原始名称，如：xxx.png
            fileName = UUIDUtil.getFileName(fileName);// 获得文件的唯一名称，同时对上传文件类型做限制，只能上传jpg和png的图片文件
            if (fileName!=null) {
                File file = new File(path, fileName);
                img.transferTo(file);
                product.setPicture(fileName);
            }
        }
        if (productSerivce.add(product)) {
            model.addAttribute("flag",1);
            model.addAttribute("info","添加成功");
        }else {
            model.addAttribute("info","添加失败");
        }
        return "info";
    }

    @GetMapping("/deleteProduct/{id}")
    public String deleteProduct(@PathVariable int id, Model model){
        if(productSerivce.delete(id)){
            model.addAttribute("flag",1);
            model.addAttribute("info","删除成功");
        }else {
            model.addAttribute("info","删除失败");
        }
        return "info";
    }

    @PostMapping("/updateProduct")
    public String updateProduct(@RequestParam("file") MultipartFile img, Product product, HttpSession session, Model model) throws IOException {

        if (img.getSize() > 0) {// 判断是否有上传文件
            String path = session.getServletContext().getRealPath("static/images");// 得到项目在服务器的真实根路径
            String fileName = img.getOriginalFilename();// 得到文件的原始名称，如：xxx.png
            fileName = UUIDUtil.getFileName(fileName);// 获得文件的唯一名称，同时对上传文件类型做限制，只能上传jpg和png的图片文件
            if (fileName!=null) {
                File file = new File(path, fileName);
                img.transferTo(file);
                product.setPicture(fileName);
            }
        }
        if (productSerivce.modify(product)) {
            model.addAttribute("flag",1);
            model.addAttribute("info","修改成功");
        }else {
            model.addAttribute("info","修改失败");
        }
        return "info";
    }

    @GetMapping("/manageNote/{page}")
    public String manageNote(@PathVariable int page, Model model) {
        if(page<1) page=1;
        model.addAttribute("list", noteService.getNotes(page, 10));
        model.addAttribute("count",noteService.countMessage());
        return "admin/note";
    }

    @GetMapping("/searchNote/{kw}")
    public String searchNote(@PathVariable("kw") String kw, Model model){
        model.addAttribute("list", noteService.searchNotes(kw));
        return "admin/note";
    }

    @PostMapping("/updateMessage")
    @ResponseBody
    public String updateMessage(Message message){
        if (noteService.updateMessage(message)) {
            return JsonUtil.success("修改成功");
        }
        return JsonUtil.failure("修改失败");
    }

    @PostMapping("updateRevert")
    @ResponseBody
    public String updateRevert(Revert revert){
        if (noteService.updateRevert(revert)) {
            return JsonUtil.success("修改成功");
        }
        return JsonUtil.failure("修改失败");
    }
    @GetMapping("/deleteMessage/{id}")
    public String deleteMessage(@PathVariable int id, Model model){
        if (noteService.deleteMessage(id)) {
            model.addAttribute("flag",1);
            model.addAttribute("info","删除成功");
        }else {
            model.addAttribute("info","删除失败");
        }
        return "info";
    }

    @GetMapping("deleteRevert/{id}")
    public String deleteRevert(@PathVariable int id, Model model){
        if (noteService.deleteRevert(id)) {
            model.addAttribute("flag",1);
            model.addAttribute("info","删除成功");
        }else {
            model.addAttribute("info","删除失败");
        }
        return "info";
    }

    @GetMapping("/managePerson/{page}")
    public String managePerson(@PathVariable int page, Model model) {
        if(page<1) page=1;
        model.addAttribute("list", personService.findAll(page,10));
        model.addAttribute("count",personService.countAll());
        return "admin/person";
    }

    @GetMapping("/searchPerson/{kw}")
    public String searchPerson(@PathVariable("kw") String kw, Model model){
        model.addAttribute("list", personService.search(kw));
        return "admin/person";
    }

    @PostMapping("updatePerson")
    @ResponseBody
    public String updatePerson(Person person){
        if (personService.modify(person)) {
            return JsonUtil.success("修改成功");
        }
        return JsonUtil.failure("修改失败");
    }
    @PostMapping("addPerson")
    @ResponseBody
    public String addPerson(Person person) {
        try {
            if (personService.signUp(person)) {
                return JsonUtil.success("添加成功");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }catch (DuplicateKeyException e){
            e.printStackTrace();
        }
        return JsonUtil.failure("添加失败");
    }

    @GetMapping("/deletePerson/{id}")
    public String deletePerson(@PathVariable String id, Model model) {
        if (personService.destroy(id)) {
            model.addAttribute("flag",1);
            model.addAttribute("info","删除成功");
        }else {
            model.addAttribute("info","删除失败");
        }
        return "info";
    }

}
